﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using UFIDA.U9.Base.FlexField.DescFlexField;
using UFIDA.U9.CBO.DTOs;
using UFIDA.U9.ISV.PUB.CustZLAPI.Model;
using UFIDA.U9.SM.Ship;
using UFIDA.U9.SM.Ship.Proxy;
using UFSoft.UBF.Business;
using UFSoft.UBF.MVC;
using UFSoft.UBF.Util.Log;

namespace UFIDA.U9.ISV.PUB.CustZLAPI
{
    /// <summary>
    /// 出货单 签收接口
    /// </summary>
    public class CustShipLineFinshController : OpenAPIController
    {
        /// <summary>
        /// 客户签收更新出货单
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public UFSoft.UBF.MVC.Common.ApiResult<ResaultData<List<ShipFinishSignInLineInfoDTOData>>> SignIn([FromBody] PramAPIModel param)
        {
            ILogger logger = LoggerManager.GetLogger("CustShipLineFinshController");
            try
            {
                logger.Error(string.Format("QueryCustomerPageController请求参数：{0}", JsonConvert.SerializeObject(param)), new object[0]);
                List<ShipFinishSignInLineInfoDTOData> returnDtos = null;
                ResaultData<List<ShipFinishSignInLineInfoDTOData>> resdata = new ResaultData<List<ShipFinishSignInLineInfoDTOData>>();

                List<SMSignInInfoDTOData> list = new List<SMSignInInfoDTOData>();
                foreach (Data item in param.data)
                {
                    //获取出货单id                    
                    ShipLine shipdata = UFIDA.U9.SM.Ship.ShipLine.Finder.FindByID(item.id);
                    FailData res = new FailData(item);
                    if (shipdata == null)
                    {
                        res.ErrMsg = "未查询到出货数据";
                        resdata.FailData.Add(res);
                    }
                    else
                    {
                        shipdata.SignInDate = param.SignDate;
                        shipdata.Signer = param.Signer;
                        SMSignInInfoDTOData signInInfo = this.CreateSignInInfo(shipdata,item.num);
                        list.Add(signInInfo);
                    }

                }

                returnDtos = new BatchSignInProxy
                {
                    SignInDTOs = list,
                    IsSumSignQty = true
                }.Do();
                resdata.Data = returnDtos;
                //foreach (ShipFinishSignInLineInfoDTOData dto in returnDtos)
                //{
                //    ShipLine record2 = UFIDA.U9.SM.Ship.ShipLine.Finder.FindByID(dto.ShipLineKey);
                //    bool flag2 = record2 != null;
                //    if (flag2)
                //    {
                //        record2.SysVersion = dto.SysVersion;
                //        record2.ConfirmDate = dto.ConfirmDate;
                //        record2.MaturityDate = dto.MaturityDate;
                //    }
                //}


                return new UFSoft.UBF.MVC.Common.ApiResult<ResaultData<List<ShipFinishSignInLineInfoDTOData>>>(resdata);
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("QueryCustomerPageController错误：{0}", ex.StackTrace));
                return new UFSoft.UBF.MVC.Common.ApiResult<ResaultData<List<ShipFinishSignInLineInfoDTOData>>>(null, -1, ex.Message);
            }
        }
        #region 处理数据

        private void GetShipFinishSignInLineInfoDTO(List<ShipFinishSignInLineInfoDTOData> lstShipLineID, ShipLine.EntityList list)
        {
            if (list != null && list.Count > 0)
            {
                foreach (ShipLine record in list)
                {

                    bool flag2 = this.IsPermitSignIn(record);
                    if (flag2)
                    {
                        lstShipLineID.Add(new ShipFinishSignInLineInfoDTOData
                        {
                            ShipLineKey = record.ID,
                            SysVersion = Convert.ToInt64(record.SysVersion)
                        });
                    }
                    else
                    {
                        throw new Exception("签收数量+拒收数量+途损数量不等于出货数量");
                    }

                }
            }
        }
        private bool IsPermitSignIn(ShipLine record)
        {

            decimal? num = record.CusSignInQtyTUAmount;//签收数量
            decimal d = 0m;
            if (!(num > d & num != null))
            {
                // 累计签收数量  签收数量 拒收数量  途损数量 出货数量
                if (record.TotalSignInQtyPU + record.CusSignInQtyTUAmount + record.RejectQtyTUAmount + record.DamageQtyTUAmount != record.ShipQtyTUAmount)
                {
                    return false;
                }
                //界面处理数据
                //num = record.RefuseTotalQtyTU;
                //d = 0m;
                //if (!(num.GetValueOrDefault() > d & num != null))
                //{
                //    num = record.RouteDamageTotalQtyTU;
                //    d = 0m;
                //    if (!(num.GetValueOrDefault() > d & num != null))
                //    {
                //        num = record.FillGoodsTotalQtyTU;
                //        d = 0m;
                //        if (!(num.GetValueOrDefault() > d & num != null))
                //        {
                //            return false;
                //        }
                //    }
                //}               
            }
            bool? isFinishSignIn = record.IsFinishSignIn;
            bool flag = true;
            return !(isFinishSignIn == flag && isFinishSignIn != null);
        }

        private SMSignInInfoDTOData CreateSignInInfo(ShipLine record,decimal num)
        {
            SMSignInInfoDTOData signInInfo = new SMSignInInfoDTOData();
            signInInfo.ShipLineID = record.ID;
            signInInfo.AccureDate = Convert.ToDateTime(record.ConfirmDate);
            signInInfo.DueDate = Convert.ToDateTime(record.MaturityDate);
            signInInfo.SignInDate = Convert.ToDateTime(record.SignInDate);
            signInInfo.SignInMan = record.Signer;
            signInInfo.RejectAmountPU = this.CreatePUQutity(record, record.RejectQtyPriceAmount);
            signInInfo.RejectAmountTU = this.GetDoubleQuantityData(record.RejectQtyTUAmount, record.RejectQtyTBUAmount, record.TradeUom.ID, record.TradeBaseUom.ID, 0L, 0L, record.TradeRatetoBase, 1m);
            signInInfo.SignInAmountIU = this.GetSingleQuantityData(num, record.InvUom.ID, record.InvBaseUom.ID, record.InvRatetoBase);
            signInInfo.SignInAmountPU = this.CreatePUQutity(record, num);
            signInInfo.SignInAmountTU = this.CreateTUDualQuantity(record, num, record.CusSignInQtyTBUAmount);

            //signInInfo.SignInAmountIU = this.GetSingleQuantityData(record.CusSignInQtyTUAmount, record.InvUom.ID, record.InvBaseUom.ID, record.InvRatetoBase);
            //signInInfo.SignInAmountPU = this.CreatePUQutity(record, record.CusSignInQtyPriceAmount);
            //signInInfo.SignInAmountTU = this.CreateTUDualQuantity(record, record.CusSignInQtyTUAmount, record.CusSignInQtyTBUAmount);
            //signInInfo.UnSignedAdditionPU = this.CreatePUQutity(record, record.FillQtyPriceAmount);
            signInInfo.UnSignedAdditionTU = this.CreateTUDualQuantity(record, record.FillQtyTUAmount, record.FillQtyTBUAmount);
            signInInfo.WastingAmountPU = this.CreatePUQutity(record, record.DamageQtyPriceAmount);
            signInInfo.WastingAmountTU = this.CreateTUDualQuantity(record, record.DamageQtyTUAmount, record.DamageQtyTBUAmount);
            signInInfo.SysVersion = Convert.ToInt64(record.SysVersion);
            signInInfo.DescFlexInfo = record.DescFlexField.ToEntityData();
            signInInfo.SignInTUPUConvRatio = record.SignInTUPUConvRatio;
            return signInInfo;
        }
        private SingleQuantityData CreatePUQutity(ShipLine lineRecord, decimal? dcmAmount)
        {
            SingleQuantityData sign = new SingleQuantityData();
            sign.Amount = Convert.ToDecimal(dcmAmount);
            sign.UOM = new UOMInfoDTOData();
            sign.UOM.UOMMain = lineRecord.PriceUom.ID;
            sign.UOM.UOMSub = lineRecord.PriceBaseUom.ID;
            sign.UOM.Rate = lineRecord.PriceRatetoBase;
            return sign;
        }
        private DoubleQuantityData GetDoubleQuantityData(decimal a1, decimal a2, long TU1, long TBU1, long TU2, long TBU2, decimal rate1, decimal rate2)
        {
            return new DoubleQuantityData(a1, a2, new UOMInfoDTOData(TU1, TU2, rate1), new UOMInfoDTOData(TU2, TBU2, rate2));
        }
        public SingleQuantityData GetSingleQuantityData(decimal a1, long mainUom, long subUom, decimal rate)
        {
            return new SingleQuantityData(a1, new UOMInfoDTOData(mainUom, subUom, rate));
        }
        private DoubleQuantityData CreateTUDualQuantity(ShipLine lineRecord, decimal? dcmAmount1, decimal? dcmAmount2)
        {
            return new DoubleQuantityData
            {
                Amount1 = Convert.ToDecimal(dcmAmount1),
                Amount2 = Convert.ToDecimal(dcmAmount2),
                UOM1 = new UOMInfoDTOData(lineRecord.TradeUom.ID, lineRecord.TradeBaseUom.ID, lineRecord.TradeRatetoBase),
                UOM2 = new UOMInfoDTOData(0L, 0L, 1m)
            };
        }

        #endregion

    }
}
